const {
  app,
  BrowserWindow,
  ipcMain
} = require('electron');
const path = require('path')
const child_process = require('child_process')

const {
  exec
} = child_process

const isPro = process.env.NODE_ENV !== "development";

// window对象的全局引用
let mainWindow;
let printers

let openExec

async function createWindow() {

  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      preload: path.join(__dirname, 'preload.js')
    }
  })

  if (isPro) {
    mainWindow.loadFile(`${__dirname}/build/index.html`);
  } else {
    mainWindow.loadURL('http://localhost:8000');
  }


  // 关闭window时触发下列事件.
  mainWindow.on('closed', function () {
    mainWindow = null
  })

  // openExec = exec('node ./server.js', (error, stdout, stderr) => {
  //   console.log(error);
  //   console.log(stdout);
  //   console.log(stderr);
  // })

  printers = await mainWindow.webContents.getPrintersAsync()
}

ipcMain.on('get-printers', async (event, _) => {
  event.reply('return-printers', printers);
});

ipcMain.on('xmf-print', async (event, args) => {
  console.log('args', args);
  mainWindow.webContents.print(args, (success, _) => {
    console.log(success);
  })
});

app.on('ready', createWindow);

// 所有窗口关闭时退出应用.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit();

    if (!openExec) {
      // console.log('openExec is null')
    } else {
      // exec('taskkill /f /t /im node.exe', function (error, stdout, stderr) {
      //   if (error) {
      //     console.log(error.stack);
      //     console.log('Error code: ' + error.code);
      //     return;
      //   }
      //   console.log('使用exec方法输出: ' + stdout);
      //   console.log(`stderr: ${stderr}`);
      // });
    }
  }
});

app.on('activate', function () {

  if (mainWindow === null) {
    createWindow();
  }
});
